package org.iss.ip.service;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.log4j.BasicConfigurator;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

@Service
public class SendCodeService {

	public  String checkCode;
    public  String inputCode;
    
    public  boolean sendCode(String num) throws ApiException {
        BasicConfigurator.configure();
        String url = "http://gw.api.taobao.com/router/rest";
        String appkey = "23558909";
        String secret = "e713e46673893aad962c94b58f60ed86";

        String json = "{\"number\":\"" + checkCode + "\"}";

        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");
        req.setSmsFreeSignName("网设风之谷团队");
        req.setSmsParamString(json);


        System.out.println("sendCode" + checkCode);

        req.setRecNum(num);
        req.setSmsTemplateCode("SMS_33645030");
        AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);

        System.out.println(rsp.getBody());
        return true;
    }

    public  String randCode() throws ApiException {
        //随机生成 6 位验证码
        String code = "";
        Random r = new Random(new Date().getTime());
        for (int i = 0; i < 6; i++) {
            code = code + r.nextInt(10);
        }
        checkCode = code;
        System.out.println("randCode:  " + checkCode);


        return code;
    }
    /**
     * 大陆号码或香港号码均可
     */
    public  boolean isPhoneLegal(String str)throws PatternSyntaxException {
        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public  boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 香港手机号码8位数，5|6|8|9开头+7位任意数
     */
    public  boolean isHKPhoneLegal(String str)throws PatternSyntaxException {
        String regExp = "^(5|6|8|9)\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
}
